package parser;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlayerParser {
	
	public static final int NUMBER_PLAYERS_PER_ROUND = 352;
	
	public static final int NAME = 1; //1;
	public static final int TEAM = 12; //2;
	public static final int SCORE = 11;
	
	private Connection connection;
	private Map<String, String> teams;
	private Map<String, String> teams2;
	private List<Player> players;
	private int preSeasonRound = -1;
	
	public void init() {
		teams = new HashMap<String, String>();
		teams2 = new HashMap<String, String>();
		populateTeams();
		populatePlayers();
		establishConnection();
	}
	
	public static void main(String[] args) {
		PlayerParser playerScoreParser = new PlayerParser();

		/*playerScoreParser.init();
		if (args.length > 0 && args[0] != null) {
			playerScoreParser.SetPreSeasonRound(Integer.valueOf(args[0]));
		}*/
		
			playerScoreParser.init();
			playerScoreParser.doIt();
	}

	private int getRound() throws SQLException {
		if (preSeasonRound > 0) {
			return preSeasonRound + 50;
		}
		
		return getUniqueInteger("select min(round) from Round where complete = false");
	}
	
	private int getUniqueInteger(String sql) {
		Statement stmt = null;
		ResultSet resultSet = null;
		int result = -1;
		try {
			stmt = connection.createStatement();
			resultSet = stmt.executeQuery(sql);
			resultSet.next();
			result = resultSet.getInt(1);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				stmt.close();
				resultSet.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
		return result;
	}
	
	private boolean isRoundFinished(int round) throws SQLException {
		int numberOfPlayersForRound = getUniqueInteger("select count(*) from PlayerScore where round = " + round);
		
		return numberOfPlayersForRound >= NUMBER_PLAYERS_PER_ROUND;
	}
	
	public void doIt() {
		FileWriter outFile = null;
		PrintWriter out = null;
		try {	
		String prevTeam = "";
		outFile = new FileWriter("c:/results2.txt");
		out = new PrintWriter(outFile);
		Statement stmt = connection.createStatement();
		ResultSet rs = stmt.executeQuery( "SELECT * FROM Player order by team, surname");
		while (rs.next()) {
			String playerType = rs.getString("playerType");
			String team = rs.getString("team");
			String playerName = rs.getString("firstName") + " " + rs.getString("surname");
			if (team != null) {
				if (!team.equals(prevTeam)) {
					out.println("");
					out.println("[b]" + teams2.get(team) + "[/b]");
				}
				if (playerType != null) {
					if (playerType.equals("KPP")) {
						out.println("[color=blue]" + playerName + "[/color](**)" + "(" + rs.getInt("id") + ")");	
					}
					else if (playerType.equals("HALF_KPP")) {
						out.println("[color=green]" + playerName + "[/color](*)" + "(" + rs.getInt("id") + ")");
					}
					else if (playerType.equals("RUCK")) {
						out.println("[color=purple]" + playerName + "[/color](***)" + "(" + rs.getInt("id") + ")");
					}
					else if (playerType.equals("KPP_RUCK")) {
						out.println("[color=red]" + playerName + "[/color](****)" + "(" + rs.getInt("id") + ")");
					}
				}
				else {
					out.println(playerName + "(" + rs.getInt("id") + ")");
				}
				
				prevTeam = team;
			}
		}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
		out.close();
		}
	}
	
	public void run() {
		BufferedReader bufRead = null;
		try {
			int round = getRound();
			
	        FileReader input = new FileReader("c:/file.txt");
			bufRead = new BufferedReader(input);
			String line = "";
			int count = 0;
			Statement stmt = connection.createStatement();
			List<String> processdTeams = new ArrayList<String>();
			
			while ((line = bufRead.readLine()) != null && count < 5) {
				String[] components = line.split("\t");
				String firstName, surname;
				surname = components[NAME].trim().substring(components[NAME].trim().indexOf(". ") + 2, components[NAME].trim().indexOf(", "));
				firstName = components[NAME].trim().substring(components[NAME].trim().indexOf(", ") + 2);

				firstName = firstName.replace("'", "''");
				surname = surname.replace("'", "''").replace(" (Injured)", "");
				
				String team = components[TEAM].trim();
				
				if (!processdTeams.contains(team)) processdTeams.add(team);
				
				int score = Integer.valueOf(components[SCORE].trim());
				
				for (Player player : players) {
					if (player.getFirstName().equals(firstName) && player.getSurname().equals(surname) && player.getTeam().equals(team)) {
						firstName = player.getRequiredFirstName();
						surname = player.getRequiredSurname();
						
						break;
					}
				}
				
				//System.out.println("firstname: [" + firstName + "], surname: [" + surname + "]");
				ResultSet rs = stmt.executeQuery( "SELECT id FROM Player where firstName = '" + firstName + "' AND surname = '" + surname + "' AND team = '" + teams.get(team) + "'");
				if (rs.next()) {
					int playerId = rs.getInt(1);
					if (rs.next()) {
						System.out.println("ERROR: more than one - " + firstName + " " + surname + "(" + team + ")");
					}
					else {
						ResultSet resultSet = stmt.executeQuery("SELECT count(*) FROM PlayerScore where round = " + round + " and playerId = " + playerId);
						resultSet.next();
						if (resultSet.getInt(1) == 0) {
							stmt.executeUpdate("INSERT INTO PlayerScore (round, playerId, score) VALUES (" + round + "," + playerId + "," + score + ")");
						}
					}
				}
				else {
					System.out.println("ERROR: not found - [" + firstName + " " + surname + "](" + team + ")");
				}
			}
			
			for (String team : processdTeams) {
				stmt.executeUpdate("INSERT INTO PlayerScore (playerId, round, score) SELECT id, " + round + ",0 from player where id not in (select playerId from PlayerScore where round = " + round + ") and team = '" + team + "'");	
			}
			
			if (isRoundFinished(round)) {
				stmt.executeUpdate("UPDATE Round set complete = true where round = " + round);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				bufRead.close();
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void populateTeams() {
		teams.put("West Coast", "WCE");
		teams.put("Richmond", "RICHMOND");
		teams.put("Geelong", "GEELONG");
		teams.put("Melbourne", "MELBOURNE");
		teams.put("Port Adelaide", "PORT_ADELAIDE");
		teams.put("St Kilda", "ST_KILDA");
		teams.put("Adelaide", "ADELAIDE");
		teams.put("North Melbourne", "NORTH_MELBOURNE");
		teams.put("Fremantle", "FREMANTLE");
		teams.put("Hawthorn", "HAWTHORN");
		teams.put("Brisbane", "BRISBANE");
		teams.put("Western Bulldogs", "WESTERN_BULLDOGS");
		teams.put("Collingwood", "COLLINGWOOD");
		teams.put("Essendon", "ESSENDON");
		teams.put("Sydney", "SYDNEY");
		teams.put("Carlton", "CARLTON");
		
		teams2.put("WCE", "West Coast");
		teams2.put("RICHMOND", "Richmond");
		teams2.put("GEELONG", "Geelong");
		teams2.put("MELBOURNE", "Melbourne");
		teams2.put("PORT_ADELAIDE", "Port Adelaide");
		teams2.put("ST_KILDA", "St Kilda");
		teams2.put("ADELAIDE", "Adelaide");
		teams2.put("NORTH_MELBOURNE", "North Melbourne");
		teams2.put("FREMANTLE", "Fremantle");
		teams2.put("HAWTHORN", "Hawthorn");
		teams2.put("BRISBANE", "Brisbane");
		teams2.put("WESTERN_BULLDOGS", "Western Bulldogs");
		teams2.put("COLLINGWOOD", "Collingwood");
		teams2.put("ESSENDON", "Essendon");
		teams2.put("SYDNEY", "Sydney");
		teams2.put("CARLTON", "Carlton");
	}
	
	private void establishConnection() {
		try {
			Class.forName( "com.mysql.jdbc.Driver" );
			connection = DriverManager.getConnection(
				     "jdbc:mysql://localhost/sffdraftgame",
				     "root",
				     "password" );

		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void SetPreSeasonRound(int preSeasonRound) {
		this.preSeasonRound = preSeasonRound;
	}
	
	public void populatePlayers() {
		players = new ArrayList<Player>();
		players.add(new Player("Lachie", "Henderson", "Carlton", "Lachlan", "Henderson"));
		players.add(new Player("Chris", "Yarran", "Carlton", "Christopher", "Yarran"));
		players.add(new Player("Scott", "D. Thompson", "North Melbourne", "Scott", "Thompson"));
		players.add(new Player("Sam", "Wright", "North Melbourne", "Samuel", "Wright"));
		players.add(new Player("Josh", "P. Kennedy", "Sydney", "Josh", "Kennedy"));
		players.add(new Player("L.", "Roberts-Thomson", "Sydney", "Lewis", "Roberts-Thomson"));
		players.add(new Player("Matt", "Maguire", "Brisbane", "Matthew", "Maguire"));
		players.add(new Player("S.", "Prestigiacomo", "Collingwood", "Simon", "Prestigiacomo"));
		players.add(new Player("Ben", "Stratton", "Hawthorn", "Benjamin", "Stratton"));
		players.add(new Player("Jefferey", "Garlett", "Carlton", "Jeff", "Garlett"));
		players.add(new Player("Lachie", "Hansen", "North Melbourne", "Lachlan", "Hansen"));
		players.add(new Player("Scott D.", "Thompson", "North Melbourne", "Scott", "Thompson"));
		players.add(new Player("Josh P.", "Kennedy", "Sydney", "Josh", "Kennedy"));
		players.add(new Player("Josh J.", "Kennedy", "West Coast", "Joshua", "Kennedy"));
		players.add(new Player("Nick", "Naitanui", "West Coast", "Nicholas", "Naitanui"));
		players.add(new Player("Matt", "Priddis", "West Coast", "Matthew", "Priddis"));
		players.add(new Player("Matt", "Rosa", "West Coast", "Matthew", "Rosa"));
		players.add(new Player("Matt", "Spangher", "West Coast", "Matthew", "Spangher"));
		players.add(new Player("Ricky", "Dyson", "Essendon", "Rick", "Dyson"));
		players.add(new Player("Matt", "White", "Richmond", "Matthew", "White"));
		players.add(new Player("Mitch", "Duncan", "Geelong", "Mitchell", "Duncan"));
		players.add(new Player("Robbie", "Gray", "Port Adelaide", "Robert", "Gray"));
		players.add(new Player("Chris", "Mayne", "Fremantle", "Christopher", "Mayne"));
		players.add(new Player("Mitch", "Clark", "Brisbane", "Mitchell", "Clark"));
		players.add(new Player("Nathan J.", "Brown", "Collingwood", "Nathan", "Brown"));
		players.add(new Player("Ben", "McKinley", "West Coast", "Benjamin", "McKinley"));
		players.add(new Player("Danny", "Hughes", "Melbourne", "Daniel", "Hughes"));
		players.add(new Player("Matt", "Suckling", "Hawthorn", "Matthew", "Suckling"));
		players.add(new Player("Chris", "Johnson", "Carlton", "Christopher", "Johnson"));
		players.add(new Player("Nick", "Suban", "Fremantle", "Nicholas", "Suban"));
		players.add(new Player("Zac", "Clarke", "Fremantle", "Zach", "Clarke"));
		players.add(new Player("Robbie", "Tarrant", "North Melbourne", "Robert", "Tarrant"));
		players.add(new Player("Andrew L.", "Browne", "Richmond", "Andrew", "Browne"));
		players.add(new Player("Benjamin", "Speight", "North Melbourne", "Ben", "Speight"));
		players.add(new Player("Brad", "Fisher", "Carlton", "Bradley", "Fisher"));
		players.add(new Player("Robbie", "Hicks", "Richmond", "Robert", "Hicks"));
		players.add(new Player("Jamie", "O'Rielly", "Richmond", "James", "O'Rielly"));
		 
	}
	
	class Player {
		private String firstName;
		private String surname;
		private String team;
		private String requiredFirstName;
		private String requiredSurname;
		
		public Player(String firstName, String surname, String team, String requiredFirstName, String requiredSurname) {
			super();
			this.firstName = firstName;
			this.surname = surname;
			this.team = team;
			this.requiredFirstName = requiredFirstName;
			this.requiredSurname = requiredSurname;
		}

		public String getFirstName() {
			return firstName;
		}
		
		public void setFirstName(String firstName) {
			this.firstName = firstName;
		}
		
		public String getSurname() {
			return surname;
		}
		
		public void setSurname(String surname) {
			this.surname = surname;
		}
		
		public String getTeam() {
			return team;
		}
		
		public void setTeam(String team) {
			this.team = team;
		}

		public String getRequiredFirstName() {
			return requiredFirstName;
		}

		public void setRequiredFirstName(String requiredFirstName) {
			this.requiredFirstName = requiredFirstName;
		}

		public String getRequiredSurname() {
			return requiredSurname;
		}

		public void setRequiredSurname(String requiredSurname) {
			this.requiredSurname = requiredSurname;
		}
		
	}
}
